//
//  ImportLinkerViewController.m
//  GC_OC
//
//  Created by xyy on 2022/5/24.
//

#import "ImportLinkerViewController.h"
#import "LinkerCell.h"
#import "OneLevelLinkerCell.h"
#import "LinkerModel.h"
#import "HelpAlertView.h"
#import "AppDelegate.h"
#import "CategoryView.h"
#import "ImportLinkerNextViewController.h"
#import <JSONModel/JSONModel.h>
#import "ChooseCategoryAlertView.h"
#import "CurriculumModel.h"

/// 外链导入
@interface ImportLinkerViewController ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, strong) UIView *navigationBarView;
@property(nonatomic, strong) ChooseCategoryAlertView *chooseCategoryAlertView;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) UIView *headerView;
@property(nonatomic, strong) UIView *toolBarView;
@property(nonatomic, strong) UIButton *editorButton;
@property(nonatomic, strong) UILabel *categoryLabel;
@property(nonatomic, strong) LinkerModel *fModel;
@property(nonatomic, strong) LinkerModel *sModel;
@property(nonatomic, strong) LinkerModel *tModel;
@property(nonatomic, strong) UILabel *f_sLabel;
@property(nonatomic, strong) UILabel *tLabel;
@property(nonatomic, strong) UIButton *playButton;
@property(nonatomic, strong) UIButton *categoryButton;
@property(nonatomic, strong) UIButton *importButton;

@end

@implementation ImportLinkerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"外链导入";
    self.view.backgroundColor = XHUIColorFromRGB(0xF6F7F9);
    
    if (self.chooseType == NO) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
        
        NSArray *array = [[NSUserDefaults standardUserDefaults] valueForKey:@"bnyt_linker"];
        if (array.count == 0) {
            LinkerModel *obj2_2 = [LinkerModel new];
            obj2_2.type = @2;
            obj2_2.name = @"默认分类";
            
            LinkerModel *obj1_1 = [LinkerModel new];
            obj1_1.type = @1;
            obj1_1.name = @"默认大分类";
            obj1_1.list = [NSMutableArray arrayWithArray:@[obj2_2]];
            
            [self.dataSource addObjectsFromArray:@[obj1_1]];
        } else {
            //字典转json
            for (NSDictionary *fDic in array) {
                NSMutableArray *fList = fDic[@"list"];
                
                LinkerModel *fObj = [LinkerModel new];
                fObj.name = fDic[@"name"];
                fObj.type = fDic[@"type"];

                NSMutableArray *sArray = [NSMutableArray arrayWithCapacity:0];

                for (NSDictionary *sDic in fList) {
                    LinkerModel *sObj = [LinkerModel new];
                    sObj.name = sDic[@"name"];
                    sObj.type = sDic[@"type"];

                    NSMutableArray *sList = sDic[@"list"];
                    NSMutableArray *tArray = [NSMutableArray arrayWithCapacity:0];
                    for (NSDictionary *tDic in sList) {
                        LinkerModel *tObj = [LinkerModel new];
                        tObj.name = tDic[@"name"];
                        tObj.url = tDic[@"url"];
                        tObj.type = tDic[@"type"];
                        [tArray addObject:tObj];
                    }
                    sObj.list = tArray;
                    [sArray addObject:sObj];
                }
                fObj.list = sArray;
                [self.dataSource addObject:fObj];
            }
        }
    }
    
    [self setupUIView];
    
    if (self.chooseType) {
        for (NSInteger i = 0; i < self.dataSource.count; i++) {
//            if (i == 0) {
//                self.dataSource[i].isFold = @1;
//                self.dataSource[i].isSelect = @1;
//
//                for (NSInteger j = 0; j < self.dataSource[i].list.count; j++) {
//                    if (j == 0) {
//                        LinkerModel *sobj = [self.dataSource[0].list firstObject];
//                        sobj.isSelect = @1;
//                    }
//                }
//            }
        }
        [self refreshCategoryTitle];
    }
    
    if (self.chooseType == NO) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUI) name:@"BNYTRefreshUI" object:nil];
    }
}

- (void)refreshUI {
    [self.tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)refreshCategoryTitle {
    for (LinkerModel *fobj in self.dataSource) {
        for (LinkerModel *sobj in fobj.list) {
            if ([sobj.isSelect isEqual:@1]) {
                self.categoryLabel.text = [NSString stringWithFormat:@"%@-%@",fobj.name, sobj.name];
            }
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:true];
    
    [self.tableView reloadData];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:true];
    
    [AppDelegate shared].audioPlayer = nil;
    [self resetUI];
}

- (void)setupUIView {
    self.navigationBarView = [UIView new];
    self.navigationBarView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.navigationBarView];
    
    UILabel *naviTitle = [UILabel new];
    naviTitle.text = @"外链导入";
//    naviTitle.textAlignment = NSTextAlignmentCenter;
    naviTitle.userInteractionEnabled = YES;
    naviTitle.textColor = [UIColor blackColor];
    naviTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.navigationBarView addSubview:naviTitle];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [naviTitle addGestureRecognizer:tap];
    
    UIButton *backButton = [UIButton new];
    [backButton setImage:[UIImage imageNamed:@"icon_返回_32_left"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:backButton];
    
    UIButton *exitButton = [UIButton new];
    self.editorButton = exitButton;
    if (self.chooseType) {
        [exitButton setTitle:@"帮助" forState:UIControlStateNormal];
    } else {
        [exitButton setTitle:@"编辑" forState:UIControlStateNormal];
        [exitButton setTitle:@"完成" forState:UIControlStateSelected];
    }
    [exitButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    exitButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [exitButton addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:exitButton];
    
    //导入音频
    UIButton *importButton = [UIButton new];
    self.importButton = importButton;
//    importButton.layer.masksToBounds = YES;
//    importButton.layer.cornerRadius = 22.5;
    if (self.chooseType) {
//        [importButton setTitle:@"确定选中" forState:UIControlStateNormal];
    } else {
//        [importButton setTitle:@"导入音频" forState:UIControlStateNormal];
    }
    [importButton setImage:[UIImage imageNamed:@"导入"] forState:UIControlStateNormal];
    [importButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    importButton.backgroundColor = XHUIColorFromRGB(0x0091FF);
    importButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [importButton addTarget:self action:@selector(importAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:importButton];
    
    UIView *view = [UIView new];
    view.backgroundColor = XHUIColorFromRGB(0xEAE0E4);
    [self.view addSubview:view];
    
    self.categoryLabel = [UILabel new];
    self.categoryLabel.textColor = [UIColor blackColor];
    self.categoryLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [view addSubview:self.categoryLabel];

    //tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    if (self.chooseType) {
        self.tableView.backgroundColor = [UIColor whiteColor];
    } else {
        self.tableView.backgroundColor = [UIColor clearColor];
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[OneLevelLinkerCell class] forCellReuseIdentifier:@"OneLevelLinkerCell"];
    [self.view addSubview:self.tableView];
    
    UIView *headerView = [UIView new];
    headerView.backgroundColor = [UIColor clearColor];
    headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 10);
    self.tableView.tableHeaderView = headerView;
    
    //toolbar
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.startPoint = CGPointMake(0, 0);
    gradient.endPoint = CGPointMake(0, 1);
    gradient.frame =CGRectMake(0,0,SCREEN_WIDTH,50);
    gradient.colors = [NSArray arrayWithObjects:(id)XHUIColorFromRGB(0xF4F4F4).CGColor,(id)XHUIColorFromRGB(0xFDFDFD).CGColor,nil];
    
    self.toolBarView = [UIView new];
    self.toolBarView.hidden = YES;
    [self.toolBarView.layer insertSublayer:gradient atIndex:0];
    [self.view addSubview:self.toolBarView];
    
    self.tLabel = [UILabel new];
    self.tLabel.textColor = [UIColor blackColor];
    self.tLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    [self.toolBarView addSubview:self.tLabel];
    
    self.f_sLabel = [UILabel new];
    self.f_sLabel.textColor = XHUIColorFromRGB(0x666666);
    self.f_sLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
    [self.toolBarView addSubview:self.f_sLabel];
    
    self.playButton = [UIButton new];
    [self.playButton setImage:[UIImage imageNamed:@"narrow_playBtn_play"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"icon_zimu_defaults"] forState:UIControlStateSelected];
    [self.playButton addTarget:self action:@selector(playAudioAction) forControlEvents:UIControlEventTouchUpInside];
    [self.toolBarView addSubview:self.playButton];
    
    self.categoryButton = [UIButton new];
    [self.categoryButton setImage:[UIImage imageNamed:@"24gf-playlistMusic"] forState:UIControlStateNormal];
    [self.categoryButton addTarget:self action:@selector(categoryAction) forControlEvents:UIControlEventTouchUpInside];
    [self.toolBarView addSubview:self.categoryButton];
    
    
    UIView *barLineView = [UIView new];
    barLineView.backgroundColor = XHUIColorFromRGB(0xE5E5E5);
    [self.toolBarView addSubview:barLineView];
                                                   
    [self.view addSubview:self.chooseCategoryAlertView];
    
    
    [self.navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(NAVI_BAR_HIGHT);
    }];
    [naviTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(100);
        make.left.equalTo(backButton.mas_right).offset(0);
        make.top.mas_equalTo(StatusBarHeight);
        make.height.mas_equalTo(40);
    }];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(32);
        make.left.equalTo(self.navigationBarView).offset(12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    [exitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(32);
        make.width.mas_equalTo(40);

        make.right.equalTo(self.navigationBarView).offset(-12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    
    [importButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(45);
        make.width.mas_equalTo(45);
        make.right.equalTo(self.view).offset(-12);
        make.bottom.equalTo(self.view).offset(-HY_BottomWhiteBar_Height -60);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(importButton.mas_top).mas_equalTo(-30);
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.navigationBarView.mas_bottom).mas_equalTo(0);
    }];
    
    if (self.chooseType) {
        [self.categoryLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).offset(30);
            make.height.mas_equalTo(44);
            make.right.top.equalTo(view);
        }];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(44);
            make.top.equalTo(self.navigationBarView.mas_bottom).mas_equalTo(0);
        }];
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.navigationBarView.mas_bottom).mas_equalTo(54);
        }];
    }

    [self.toolBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(50);
    }];
    [barLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.left.right.top.mas_equalTo(0);
    }];

    [self.tLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(16);
        make.left.equalTo(self.toolBarView).offset(14);
        make.top.equalTo(self.toolBarView).offset(7);
        make.width.greaterThanOrEqualTo(@200);

    }];
    [self.f_sLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(14);
        make.left.equalTo(self.toolBarView).offset(14);
        make.top.equalTo(self.tLabel.mas_bottom).offset(5);
        make.width.greaterThanOrEqualTo(@200);
    }];
    [self.categoryButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(27);
        make.right.equalTo(self.toolBarView).offset(-17);
        make.centerY.equalTo(self.toolBarView).offset(0);
        make.width.mas_equalTo(19);
    }];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(32);
        make.right.equalTo(self.categoryButton.mas_left).offset(-23);
        make.centerY.equalTo(self.toolBarView).offset(0);
        make.width.mas_equalTo(32);
    }];
}
- (void)back {
    if (self.chooseType == NO) {
        //保存三级分类到本地
        
        NSMutableArray *fDicArray = [NSMutableArray arrayWithCapacity:0];

        for (LinkerModel *fObj in self.dataSource) {
            NSMutableDictionary *fDic = [NSMutableDictionary dictionaryWithCapacity:0];
            fDic[@"type"] = fObj.type;
            fDic[@"name"] = fObj.name;
            
            
            NSMutableArray *sDicArray = [NSMutableArray arrayWithCapacity:0];
            for (LinkerModel *sObj in fObj.list) {
                NSMutableDictionary *sDic = [NSMutableDictionary dictionaryWithCapacity:0];
                sDic[@"type"] = sObj.type;
                sDic[@"name"] = sObj.name;
                
                NSMutableArray *tDicArray = [NSMutableArray arrayWithCapacity:0];
                for (LinkerModel *tObj in sObj.list) {
                    NSMutableDictionary *tDic = [NSMutableDictionary dictionaryWithCapacity:0];
                    tDic[@"type"] = tObj.type;
                    tDic[@"name"] = tObj.name;
                    tDic[@"url"] = tObj.url;
                    [tDicArray addObject:tDic];
                }
                
                sDic[@"list"] = tDicArray;
                
                [sDicArray addObject:sDic];
            }
            
            fDic[@"list"] = sDicArray;
            
            [fDicArray addObject:fDic];
        }
//        NSLog(@"%@",fDicArray);
        
        [[NSUserDefaults standardUserDefaults] setValue:fDicArray forKey:@"bnyt_linker"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    [self.navigationController popViewControllerAnimated:YES];
    if (self.navigationController.viewControllers.count == 1) {
        if ([ICMusicPlayManager sharedManager].narrowView) {
            [ICMusicPlayManager sharedManager].narrowView.frame = CGRectMake(0, SCREEN_HEIGHT - 50 - GCtabbarHeight, SCREEN_WIDTH, 50);
        }
    }
}
- (void)editAction {
    if (self.chooseType) {
        //帮助
        HelpAlertView *alerView = [HelpAlertView new];
        [alerView showIn:self.view];
        return;
    }
    [self resetUI];
    [self.editorButton setSelected:!self.editorButton.selected];
    [self.tableView reloadData];
//    [self showToolBar:NO];
    
}

- (void)resetUI {
    [self showToolBar:NO];
    if (self.sModel) {
        self.sModel.isFold = @0;
        self.sModel.isSelect = @0;
    }
    if (self.tModel) {
        self.tModel.isSelect = @0;
    }

    self.fModel = nil;
    self.sModel = nil;
    self.tModel = nil;
    self.playButton.selected = NO;
    [self.tableView reloadData];
}
- (void)importAction {
    LinkerModel *fModel;
    LinkerModel *sModel;
    for (LinkerModel *obj in self.dataSource) {
        for (LinkerModel *model in obj.list) {
            if ([model.isSelect isEqual:@1]) {
                fModel = obj;
                sModel = model;
            }
        }
    }
    
    if (fModel && sModel) {
        ImportLinkerNextViewController *vc = [ImportLinkerNextViewController new];
        vc.fModel = fModel;
        vc.sModel = sModel;
        vc.dataSource = self.dataSource;
        [self.navigationController pushViewController:vc animated:true];
    } else {
        //弹窗选择二级分类
        self.chooseCategoryAlertView.dataSource = self.dataSource;
        [self.chooseCategoryAlertView showIn:self.view];
        __weak typeof(self) ws = self;
        self.chooseCategoryAlertView.confirmBlock = ^{
            //确定选中
            LinkerModel *fModel;
            LinkerModel *sModel;
            for (LinkerModel *obj in ws.dataSource) {
                for (LinkerModel *model in obj.list) {
                    if ([model.isSelect isEqual:@1]) {
                        fModel = obj;
                        sModel = model;
                    }
                }
            }
            if (fModel && sModel) {
                ImportLinkerNextViewController *vc = [ImportLinkerNextViewController new];
                vc.fModel = fModel;
                vc.sModel = sModel;
                vc.dataSource = ws.dataSource;
                [ws.navigationController pushViewController:vc animated:true];
            }
        };
    }
    
    
}

- (void)showToolBar:(BOOL) isShow {
//    if (self.toolBarView.hidden == NO) {
//        return;
//    }
    
    self.tLabel.text = self.tModel.name;
    self.f_sLabel.text = [NSString stringWithFormat:@"%@-%@",self.fModel.name, self.sModel.name];
    
    
    self.toolBarView.hidden = isShow == NO;
        
   
    if (isShow == YES && self.tModel) {
        self.importButton.hidden = YES;
        //播放音频
        [self.view showHUD];

//        self.tModel.url = @"http://chiatsolar.com/音频/专题/朱牧师讲道/【经典】/1688.【经典】耶稣的十字架.mp3";
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[AppDelegate shared] playAudioSound:self.tModel.url];

            __weak typeof(self) ws = self;

//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                //模拟播放完成
//                [[AppDelegate shared] stopAudioPlay];
//                [AppDelegate shared].audioPlayFinish();
//            });

            [AppDelegate shared].audioPlayFinish = ^{
                NSLog(@"🍎🍎🍎 音频播放完成");
                NSInteger tIndex = [ws.sModel.list indexOfObject:ws.tModel];
                if (tIndex == ws.sModel.list.count - 1) {
                    //最后一个就暂停播放
                    ws.playButton.selected = YES;
                    ws.tModel.isSelect = @0;
                    [ws.tableView reloadData];
                } else {
                    //如果不是最后一个，就自动播放下一个
                    ws.tModel.isSelect = @0;

                    LinkerModel *nextModel = ws.sModel.list[tIndex + 1];
                    ws.tModel = nextModel;
                    ws.tModel.isSelect = @1;
                    [ws.tableView reloadData];
                    [ws showToolBar:YES];

                    CategoryView *view = (CategoryView *)[ws.view viewWithTag:5000];
                    [view.tableView reloadData];
                }
            };

            [self.view hideBusyHUD];

        });

    } else {
        self.importButton.hidden = NO;
        [[AppDelegate shared] stopAudioPlay];
    }
    [self.toolBarView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(isShow ? -HY_BottomWhiteBar_Height : 50);
    }];
    
}

- (void)tapHeaderView:(NSArray *) infoArray index:(NSInteger) index {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    
    for (NSInteger i = 0; i < infoArray.count; i++) {
        NSDictionary *info = infoArray[i];
        
        NSMutableDictionary *tempInfo = [NSMutableDictionary dictionaryWithDictionary:info];
                
        tempInfo[@"isFold"] = @0;
        tempInfo[@"isSelect"] = @0;
        if (index == i) {
            tempInfo[@"isFold"] = @1;
            tempInfo[@"isSelect"] = @1;
        }
        [array addObject:tempInfo];
    }
    [self.dataSource removeAllObjects];
    self.dataSource = array;
    [self.tableView reloadData];
}

- (void)playAudioAction {
    [self.playButton setSelected:!self.playButton.selected];
    
    if (self.playButton.selected) {
        //暂停
        [[AppDelegate shared] pauseAudioPlay];
    } else {
        //播放
        [[AppDelegate shared] playAudio];
        if ([self.tModel.isSelect isEqual:@0]) {
            self.tModel.isSelect = @1;
            [self.tableView reloadData];
        }
    }
}

- (void)categoryAction {
    CategoryView *view = [CategoryView new];
    view.tag = 5000;
    [view showIn:self.view];
    
    view.dataSource = self.sModel.list;
    [view.tableView reloadData];
    
    __weak typeof(self) ws = self;
    
    view.tapCategoryBlock = ^(LinkerModel * _Nonnull obj, CategoryView *view) {
        for (LinkerModel *obj in ws.dataSource) {
            for (LinkerModel *sobj in obj.list) {
                for (LinkerModel *tobj in sobj.list) {
                    tobj.isSelect = @0;
                }
            }
        }
        ws.tModel = obj;
        
        [ws showToolBar:YES];
        
        obj.isSelect = @1;
        [ws.tableView reloadData];
        [view.tableView reloadData];

    };
}

#pragma mark - tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    LinkerModel *obj = self.dataSource[section];
    if ([obj.isFold isEqual:@0]) {
        return 0;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OneLevelLinkerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OneLevelLinkerCell"];
//    if (indexPath.row == 0) {
//        cell.backgroundColor = [UIColor greenColor];
//    }
     LinkerModel *info = self.dataSource[indexPath.section];
    cell.indexPath = indexPath;
    cell.fdataSource = self.dataSource;
    cell.isEditor = self.editorButton.selected;
    cell.chooseType = self.chooseType;
    [cell configCell:info.list];
    
    __weak typeof(self) ws = self;

    cell.tapTwoLevelBlock = ^(NSInteger findex, NSInteger sindex) {
        if (ws.editorButton.selected == YES) {
            return;
        }
        
        
        for (LinkerModel *obj in ws.dataSource) {
            obj.isSelect = @0;
            if (self.chooseType) {
                NSInteger i = [ws.dataSource indexOfObject:obj];
                if (i != findex) {
                    obj.isSelect = @0;
                } else {
                    obj.isSelect = @1;
                }
            }
            
            for (LinkerModel *sobj in obj.list) {
                sobj.isSelect = @0;
                if (self.chooseType) {
                    sobj.isSelect = @0;
                }
                
                for (LinkerModel *tobj in sobj.list) {
//                    tobj.isSelect = @0;
                }
            }
            
        }
        
        LinkerModel *obj = ws.dataSource[findex];
        LinkerModel *sobj = obj.list[sindex];
        if (!self.chooseType) {
            sobj.isFold = [sobj.isFold isEqual:@0] ? @1 : @0;
        }
        sobj.isSelect = [sobj.isSelect isEqual:@0] ? @1: @0;
        if ([sobj.isSelect isEqual:@1]) {
            obj.isSelect = @1;
        }
        [ws.tableView reloadData];
        
//        [ws showToolBar:NO];
        
        if (ws.chooseType) {
            [ws refreshCategoryTitle];
        }
    };

    cell.tapThirdLevelBlock = ^(NSInteger findex, NSInteger sindex, NSInteger tindex) {
        for (LinkerModel *obj in ws.dataSource) {
            for (LinkerModel *sobj in obj.list) {
                for (LinkerModel *tobj in sobj.list) {
                    tobj.isSelect = @0;
                }
            }
        }
        
        for (NSInteger i = 0; i < ws.dataSource.count; i++) {
            if (i != findex) {
                ws.dataSource[i].isSelect = @0;
                
                LinkerModel *fobj = ws.dataSource[i];
                for (NSInteger j = 0; j < fobj.list.count; j++) {
                    LinkerModel *sobj = fobj.list[j];
                    sobj.isSelect = @0;
                }
            } else {
                LinkerModel *fobj = ws.dataSource[i];
                for (NSInteger j = 0; j < fobj.list.count; j++) {
                    if (j != sindex) {
                        LinkerModel *sobj = fobj.list[j];
                        sobj.isSelect = @0;
                    }
                }
            }
        }
        
        
        LinkerModel *obj = ws.dataSource[findex];
        LinkerModel *sobj = obj.list[sindex];
        LinkerModel *tobj = sobj.list[tindex];
        obj.isSelect = @1;
        sobj.isSelect = @1;
        tobj.isSelect = @1;
        [ws.tableView reloadData];

        ws.fModel = obj;
        ws.sModel = sobj;
        ws.tModel = tobj;

        [ws showToolBar:YES];

    };
    
    cell.editorBlock = ^{
        [ws.tableView reloadData];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 38;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    LinkerModel *info = self.dataSource[section];
    NSString *name = info.name;

    UIView *hView = [UIView new];
    hView.tag = 2000 + section;
    hView.backgroundColor = [UIColor clearColor];

    UITapGestureRecognizer *hTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHeaderView:)];
    [hView addGestureRecognizer:hTap];

    
    UIView *vline = [UIView new];
    vline.backgroundColor = XHUIColorFromRGB(0x979797);
    [hView addSubview:vline];
    
    UIView *hline = [UIView new];
    hline.backgroundColor = XHUIColorFromRGB(0x979797);
    [hView addSubview:hline];
    
    UIView *aidvline = [UIView new];
    aidvline.backgroundColor = XHUIColorFromRGB(0x979797);
    [hView addSubview:aidvline];
    
    UILabel *hTitle = [UILabel new];
    if ([info.isSelect isEqual:@1] && self.editorButton.selected == NO) {
        hTitle.textColor = XHUIColorFromRGB(0x0091FF);
    } else {
        hTitle.textColor = [UIColor blackColor];
    }
    hTitle.text = name;
    hTitle.font = [UIFont systemFontOfSize:20 weight:UIFontWeightMedium];
    [hView addSubview:hTitle];

    //添加
    UIButton *addButton = [UIButton new];
    [addButton setImage:[UIImage imageNamed:@"icon_返回_32_line备份_3"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
    [hView addSubview:addButton];
    //删除
    UIButton *deleteButton = [UIButton new];
    [deleteButton setImage:[UIImage imageNamed:@"icon_返回_32_line备份_2"] forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    [hView addSubview:deleteButton];
    //编辑
    UIButton *editButton = [UIButton new];
    [editButton setImage:[UIImage imageNamed:@"icon_重命名_24_line备份"] forState:UIControlStateNormal];
    [editButton addTarget:self action:@selector(editorAction:) forControlEvents:UIControlEventTouchUpInside];
    [hView addSubview:editButton];

    [hline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hView).offset(35);
        make.centerY.equalTo(hView);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(7);
    }];
    [vline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hline);
        make.top.equalTo(hline.mas_bottom).offset(0);
        make.bottom.equalTo(hView);
        make.width.mas_equalTo(1);
    }];
    
    [aidvline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hline);
        make.top.equalTo(hView);
        make.height.mas_equalTo(19);
        make.width.mas_equalTo(1);
    }];
    
    [hTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hView).offset(43);
        make.centerY.equalTo(hView);
        make.height.mas_equalTo(18);
//        make.right.equalTo(hView).offset(-20);
    }];
    
    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hTitle.mas_right).offset(12);
        make.centerY.equalTo(hTitle);
        make.height.width.mas_equalTo(24);
    }];

    [deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(addButton.mas_right).offset(5);
        make.centerY.equalTo(hTitle);
        make.height.width.mas_equalTo(24);

    }];

    [editButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(deleteButton.mas_right).offset(5);
        make.centerY.equalTo(hTitle);
        make.height.width.mas_equalTo(24);
    }];
    
    aidvline.hidden = NO;
    vline.hidden = NO;
    if (section == 0) {
        aidvline.hidden = YES;
    }
    if (section == self.dataSource.count - 1) {
        vline.hidden = YES;
    }
    
    addButton.hidden = YES;
    deleteButton.hidden = YES;
    editButton.hidden = YES;
    if (self.editorButton.selected == YES) {
        addButton.hidden = NO;
        deleteButton.hidden = NO;
        editButton.hidden = NO;
    }
    
    hline.hidden = NO;
    if (self.dataSource.count == 1) {
        hline.hidden = YES;
    }
    
    return hView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //计算行高
    LinkerModel *userInfo = self.dataSource[indexPath.section];
    NSMutableArray *list = userInfo.list;
    CGFloat towLevelHeight = list.count * 38;
    
    for (LinkerModel *info in list) {
        NSNumber *isFold = info.isFold;
        NSArray *tempList = info.list;
        if ([isFold isEqual:@1]) {
            towLevelHeight += 40 * tempList.count;
        }
    }
    
    return towLevelHeight;
}

- (void)tapHeaderView:(UIGestureRecognizer *) sender {
    UIView *hView = sender.view;
    NSInteger index = hView.tag - 2000;
    
    for (LinkerModel *obj in self.dataSource) {
        if ([self.dataSource indexOfObject:obj] != index) {
            obj.isSelect = @0;
            for (LinkerModel *sObj in obj.list) {
                sObj.isSelect = @0;
            }
        }
    }
    LinkerModel *obj = self.dataSource[index];
    if ([obj.isFold isEqual:@1]) {
        obj.isFold = @0;
    } else {
        obj.isFold = @1;
    }
    if ([obj.isSelect isEqual:@1]) {
        obj.isSelect = @0;
    } else {
        obj.isSelect = @1;
    }
    [self.tableView reloadData];
}

- (void)addAction:(UIButton *) sender {
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"创建一级分类" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [controller addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入分类名称";
        textField.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
        textField.textColor = [UIColor blackColor];
    }];

    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *tf = controller.textFields.firstObject;
        if (tf.text.length != 0) {
            LinkerModel *obj2 = [LinkerModel new];
            obj2.type = @2;
            obj2.name = @"默认分类";
            
            LinkerModel *obj1 = [LinkerModel new];
            obj1.type = @1;
            obj1.name = tf.text;
            obj1.list = [NSMutableArray arrayWithArray:@[obj2]];
            
            [self.dataSource addObject:obj1];
            
            [self.tableView reloadData];
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [controller addAction:cancel];
    [controller addAction:confirm];
    [self presentViewController:controller animated:YES completion:nil];
}
- (void)deleteAction:(UIButton *) sender {
    NSInteger index = sender.superview.tag - 2000;
    
    NSString *name = self.dataSource[index].name;
    
    if (self.dataSource.count == 1) {
        UIAlertAction *delete = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"至少保留一个一级分类" preferredStyle:UIAlertControllerStyleAlert];
        [controller addAction:delete];
        [self presentViewController:controller animated:YES completion:nil];

        return;
    }
    
    UIAlertAction *delete = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.dataSource removeObjectAtIndex:index];
        [self.tableView reloadData];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"您确定要删除%@吗?", name] preferredStyle:UIAlertControllerStyleAlert];
    [controller addAction:cancel];
    [controller addAction:delete];

    [self presentViewController:controller animated:YES completion:nil];
}
- (void)editorAction:(UIButton *) sender {
    NSInteger index = sender.superview.tag - 2000;

    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"修改分类名称" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [controller addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入名称";
        textField.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
        textField.textColor = [UIColor blackColor];
    }];

    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *tf = controller.textFields.firstObject;
        if (tf.text.length != 0) {
            self.dataSource[index].name = tf.text;
            [self.tableView reloadData];
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [controller addAction:cancel];
    [controller addAction:confirm];
    [self presentViewController:controller animated:YES completion:nil];
}

- (ChooseCategoryAlertView *)chooseCategoryAlertView {
    if (!_chooseCategoryAlertView) {
        _chooseCategoryAlertView = [ChooseCategoryAlertView new];
    }
    return _chooseCategoryAlertView;
}
@end
